<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validate-trigger="submit" :label-width="100" :label-align="'right'"
			err-show-type="toast">
			<view class="list">
				<uni-forms-item name="goods_sn" label="货品编码" required>
					<uni-easyinput placeholder="货品编码" v-model="formData.goods_sn" trim="both"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="name" label="货品名称" required><uni-easyinput placeholder="货品名称"
						v-model="formData.name" trim="both"></uni-easyinput></uni-forms-item>
				<uni-forms-item name="type" label="规格型号" required><uni-easyinput placeholder="规格型号"
						v-model="formData.type" trim="both"></uni-easyinput></uni-forms-item>
				<uni-forms-item name="danwei" label="计量单位" required>
					<uni-easyinput placeholder="计量单位" v-model="formData.danwei"
						trim="both"></uni-easyinput></uni-forms-item>
				<uni-forms-item name="position" label="货品位置" required>
					<uni-easyinput placeholder="货品位置" v-model="formData.position"
						trim="both"></uni-easyinput></uni-forms-item>
				<uni-forms-item name="unit_id" label="进货单位" required>
					<uni-data-select collection="unit" field="_id as value, name as text" @change="change"
						v-model="formData.unit_id" :localdata="range"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="keywords" label="关键字">
					<uni-easyinput placeholder="商品关键字，为搜索引擎收录使用" v-model="formData.keywords"
						trim="both"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="jh_time" label="交货期">
					<uni-easyinput placeholder="货品名称" v-model="formData.jh_time" trim="both"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="all_price" label="版本号" required><uni-easyinput placeholder="版本号"
						v-model="formData.all_price"></uni-easyinput></uni-forms-item>
			</view>
			<view class="list">

				</uni-forms-item><uni-forms-item name="wqx_count" label="未清洗">
					<uni-easyinput @input="wqx_countEd" placeholder="未清洗" type="number"
						v-model="formData.wqx_count"></uni-easyinput>
				</uni-forms-item>
				</uni-forms-item><uni-forms-item name="yqx_count" label="已清洗">
					<uni-easyinput placeholder="已清洗" type="number" v-model="formData.yqx_count"
						@input="yqx_countEd"></uni-easyinput>
				</uni-forms-item>
				</uni-forms-item><uni-forms-item name="qx_type" label="清洗方式">
					<uni-easyinput placeholder="清洗方式" v-model="formData.qx_type"></uni-easyinput>
				</uni-forms-item>
				</uni-forms-item><uni-forms-item name="moq" label="MOQ">
					<uni-easyinput placeholder="MOQ" type="number" v-model="formData.moq"></uni-easyinput>
				</uni-forms-item>
				</uni-forms-item><uni-forms-item name="qx_price" label="清洗价格">
					<uni-easyinput placeholder="清洗价格" type="number" v-model="formData.qx_price"></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="goods_desc" label="产品中文描述"><uni-easyinput placeholder="产品中文描述"
						v-model="formData.goods_desc" trim="both"></uni-easyinput></uni-forms-item>
				<uni-forms-item name="remain_count" label="库存数量" required>
					<uni-easyinput placeholder="库存数量" type="number" v-model="formData.remain_count"
						@input="remain_countEd"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="price" label="成本单价" required><uni-easyinput placeholder="成本单价" type="number"
						v-model="formData.price"></uni-easyinput></uni-forms-item>
				<uni-forms-item name="shop_price" label="未税单价" required><uni-easyinput placeholder="未税单价" type="number"
						v-model="formData.shop_price"></uni-easyinput></uni-forms-item>


			</view>
			<view class="list">


				<uni-forms-item name="sale_price" label="销售金额"><uni-easyinput placeholder="销售金额" type="number"
						v-model="formData.sale_price"></uni-easyinput></uni-forms-item>
				<uni-forms-item name="sale_num" label="销售数量"><uni-easyinput placeholder="销售数量" type="number"
						v-model="formData.sale_num"></uni-easyinput></uni-forms-item>
				<uni-forms-item name="goods_fj" label="货品附件">
					<uni-file-picker v-model="formData.goods_fj" fileMediatype="all" :multiple="true" :max="5"
						:size="10" :file-type="['file']" :extensions="['.zip', '.rar','.7z']" :show-delete="true"
						mode="grid" @select="select" @progress="progress" @success="success" @fail="fail" />

				</uni-forms-item>
				<view class="uni-button-group"><button type="primary" class="uni-button" @click="submit">提交</button>
				</view>
			</view>

		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/opendb-mall-goods.js';
	// 用于控制防抖的定时器
	let debounceTimer = null;

	const db = uniCloud.database();
	const dbCollectionName = 'opendb-mall-goods';

	function getValidator(fields) {
		let result = {};
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key];
			}
		}
		return result;
	}

	export default {
		data() {
			let formData = {
				jh_time: '',
				category_id: '',
				goods_sn: '',
				price: 0,
				all_price: '',
				danwei: '个',
				name: '',
				type: '',
				unit: '',
				keywords: '',
				goods_desc: '',
				goods_fj: [],
				goods_thumb: '',
				goods_banner_imgs: [],
				remain_count: 0,
				zm_count: 0,
				wqx_count: 0,
				yqx_count: 0,
				qx_type: '',
				moq: 0,
				qx_price: 0,
				sale_price: 0,
				sale_num: 0,
				month_sell_count: 0,
				total_sell_count: 0,
				comment_count: 0,
				is_real: null,
				is_on_sale: null,
				is_alone_sale: null,
				is_best: null,
				is_new: null,
				is_hot: null,
				add_date: null,
				last_modify_date: null,
				seller_note: '',
				shop_price: 0
			};
			return {
				formDataId: -1,
				imageValue: [],
				formData,
				range: [],
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			};
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id;
				this.formDataId = id;
				this.getDetail(id);
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules);
		},
		methods: {

			wqx_countEd(e) {
				// 如果定时器存在，清除上次的定时器
				if (debounceTimer) {
					clearTimeout(debounceTimer);
				}
				// 设置新的定时器，在1000毫秒后执行函数
				debounceTimer = setTimeout(() => {
					// 执行逻辑
					this.formData.yqx_count = this.formData.remain_count - e;
				}, 1000); // 这里是防抖的延迟时间，1000毫秒（1秒）
			},

			yqx_countEd(e) {
				// 如果定时器存在，清除上次的定时器
				if (debounceTimer) {
					clearTimeout(debounceTimer);
				}
				// 设置新的定时器，在1000毫秒后执行函数
				debounceTimer = setTimeout(() => {
					// 执行逻辑
					this.formData.wqx_count = this.formData.remain_count - e;
				}, 1000); // 这里是防抖的延迟时间，1000毫秒（1秒）
			},
			//库存数量修改事件
			remain_countEd() {
				// 如果定时器存在，清除上次的定时器
				if (debounceTimer) {
					clearTimeout(debounceTimer);
				}
				// 设置新的定时器，在1000毫秒后执行函数
				debounceTimer = setTimeout(() => {
					if (this.formData.yqx_count != 0) {
						this.formData.wqx_count = this.formData.wqx_count + (this.formData
							.remain_count - this
							.formData.wqx_count - this.formData.yqx_count)


					} else {
						this.formData.wqx_count = this.formData.remain_count

					}


				}, 1000); // 这里是防抖的延迟时间，1000毫秒（1秒）
			},

			// 获取上传状态
			select(e) {
				console.log('选择文件：', e)
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {
				console.log('上传成功', e)
				// this.formData.goods_fj = e.tempFiles[0].url
				console.log(e.tempFiles[0].url, this.formData);
			},

			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			change(e) {
				console.log(e);
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				});

				this.$refs.form
					.validate()
					.then(res => {
						return this.submitForm(res);
					})
					.catch(() => {})
					.finally(() => {
						uni.hideLoading();
					});
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				if (this.formDataId == -1) {
					db.collection(dbCollectionName)
						.add(value)
						.then(res => {
							uni.showToast({
								title: '新增成功'
							});
							this.getOpenerEventChannel().emit('refreshData');
							setTimeout(() => uni.navigateBack(), 500);
						})
						.catch(err => {
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							});
						})
						.finally(() => {
							uni.hideLoading();
						});
				} else {

					return db
						.collection(dbCollectionName)
						.doc(this.formDataId)
						.update(value)
						.then(res => {
							uni.showToast({
								icon: 'none',
								title: '修改成功'
							});
							this.getOpenerEventChannel().emit('refreshData');
							setTimeout(() => uni.navigateBack(), 500);
						})
						.catch(err => {
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							});
						});
				}


			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				});

				db.collection(dbCollectionName)
					.doc(id)
					.get()
					.then(res => {
						const data = res.result.data[0];
						if (data) {
							this.formData = data;
						}
					})
					.catch(err => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						});
					})
					.finally(() => {
						uni.hideLoading();
					});
			}
		}
	};
</script>

<style scoped>
	.uni-container {
		padding: 15px;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;
	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 50px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
	}

	.uni-button {
		width: 184px;
	}

	.uni-app--showleftwindow .uni-container .uni-forms {
		max-width: 100%;
	}

	::v-deep uni-form span {
		display: flex;
		width: 100%;
	}
	.list{
		margin-right: 2%;
	}
</style>